/*全局变量*/
var prefix = "/approval";
var dataFlag = false;
var pageInit = null;
var initPageSize = 50;
var wrapper = new Vue({
	el : '#content',
	data : {
		total : 0,
        selectRowsTotal: 0,
        selectAppLineIds: [],
        title:'',
        author:'',
        receiptDate:'',
        submissionDate:'',
        creationDate:'',
        approvalDate:''
	},
    watch:{
	    selectRowsTotal: function (newValue, oldValue) {
	        if(newValue == 0){
	           $("#selectCkDiv").hide();
	           $("#notSelectCkDiv").show();
            }else{
                $("#notSelectCkDiv").hide();
                $("#selectCkDiv").show();
            }
        }
    }
});
/*公共方法*/
$(function() {
    $('#dataTable').attr('data-height','100%-26');
    
    $('#searchName').on('input',function () {
        if($('#searchName').val().length >0){
            $('.main_search').addClass('open');
            $('#searchName').attr('aria-expanded',true);
        }else{
            $('.main_search').removeClass('open');
            $('#searchName').attr('aria-expanded',false);
        }
    });

    $('.main_search').blur(function () {
        $('.main_search').removeClass('open');
        $('#searchName').attr('aria-expanded',false);
    });

    $('#searchName').focus(function () {
        $(".main_search").css('border-color','#0096D6')
        $(".searchIcon").css('color','#0096D6')

        if ($('#searchName').val().length > 0) {
            $('.main_search').addClass('open');
            $('#searchName').attr('aria-expanded',true);
        }
    });

    $('#searchName').blur(function () {
        $(".main_search").css('border-color','#ccc')
         $(".searchIcon").css('color','#888')
    });

    $(document).bind("click", function( e ) {
        if(e.target.id !== 'searchName') {
            $('.main_search').removeClass('open');
            $('#searchName').attr('aria-expanded', false);
        }
      });

	load();
    $(".fixed-table-pagination").remove();
	$(".fixed-table-loading").remove();

	//search event
	$(".main_search span").bind("click",clickSearchEvent);
    $("#searchName").bind("keypress",searchEvent);


    $(".main_toal_select #statusSelect li").bind("click",clickStatusSelectEvent);
    $(".main_toal_select #ctgSelect li").bind("click",clickCtgSelectEvent);

	$(".detail_btn").bind("click",detailEvent);
    $(".refresh_btn").bind("click",refreshEvent);
	//$("#centerDetail").bind("dblclick",collapsewest);
	$("#foldBtn").bind("click",foldEvent);
	$("#foldTopBtn").bind("click",foldTopEvent);
	$("#printBtn").bind("click",printEvent);

	$('#myRange').bind('input propertychange', function() {
        $('.summernote').css('zoom',$(this).val()/100)
    });

	$("#collapseBtn").bind("click",collapseBox);

    $(".fa-paperclip").on('click', function(){
       $("#attachmentInfo").toggle();
    });

    $("#attachmentList").on('click', '#operation', function(){
               $(this).closest('li').find('#fileUrl')[0].click();
           });

    pageInit = $('#dataTable').bootstrapTable('getOptions').pageNumber + 1;

    $("table").on("post-header.bs.table",function() {
        $('.fixed-table-body').on("scroll", function () {
            console.log($(this).scrollTop() + $(this).innerHeight() - $(this)[0].scrollHeight)
            if($(this).scrollTop() + $(this).innerHeight()>=$(this)[0].scrollHeight)
            {
              loadMoreData();
            }
          });
    });

    $("#dataTable").on("click",".dropdown-menu.mark li",saveMark);
    $(".detailMark").on("click",".dropdown-menu li",saveMark);

    $("#searchName").bind('input propertychange', function(){
        wrapper.title=$('#searchName').val();
        wrapper.author=$('#searchName').val();

        if($('#searchName').val()==''){
            wrapper.receiptDate='20180101';
            wrapper.submissionDate='20180101';
            wrapper.creationDate='20180101';
            wrapper.approvalDate='20180101';
        }else{
            wrapper.receiptDate=$('#searchName').val();
            wrapper.submissionDate=$('#searchName').val();
            wrapper.creationDate=$('#searchName').val();
            wrapper.approvalDate=$('#searchName').val();
        }
    })

    $(".search").on("click","li",searchByOpt)

    $('.easy-area').hover(function () {
        $('.easyLi').siblings('li').css('display','list-item')
    },function () {
        $('.easyLi').siblings('li').css('display','none')
    })
});

function saveMark() {
    let appLineId = $(this).parent().data('value');
    let color = $(this).data('color');
    let value = $(this).data('value');
    let currentLineId = $("#appLineIdSpan").text();
    $(this).parent().parent().find('>i').css('color', color);


    $.ajax({
        url : prefix + "/updateCategory",
        type : 'put',
        async:false,
        data:{
            category:value,
            appLineId:appLineId
        },
        success : function(r) {
            if (r.code == 0) {
                if (appLineId ==currentLineId){
                    $(".detailMark").find('>i').css('color', color);
                }
                $('#dataTable').bootstrapTable('refresh');
            } else {
                alert(r.msg)
            }
        }
    });

}

function loadMoreData() {
    $.ajax({
        url : $('#dataTable').bootstrapTable('getOptions').url,
        type : 'get',
		async:false,
		data:{
            pageSize : 20,
            pageNum : pageInit,
            title : $('#searchName').val(),
            orderBy:'create_time desc',
            isDelete: 'N'
		},
        success : function(data) {
            if (data.list != undefined && data.list.length > 0) {
                pageInit++
                $('#dataTable').bootstrapTable('append', data.list);
            }
        }
    });
}

function loadApprovalLines(appId) {
	$('#approvalLinesTable')
		.bootstrapTable(
			{
				method : 'get', // 服务器数据的请求方式 get or post
				url : prefix + '/query/listLines', // 服务器数据的加载地址
                cache: false,
				//	showRefresh : true,
				//	showToggle : true,
				locale: "zh-CN",
				//locale: "en-US",
				//locale: "ko-KR",
				iconSize : 'outline',
				toolbar : '#exampleToolbar',
				striped : false, // 设置为true会有隔行变色效果
				dataType : "json", // 服务器返回的数据类型
				pagination : false, // 设置为true会在底部显示分页条
				// queryParamsType : "limit",
				// //设置为limit则会发送符合RESTFull格式的参数
				singleSelect : false, // 设置为true将禁止多选
				// contentType : "application/x-www-form-urlencoded",
				// //发送到服务器的数据编码类型
				//search : true, // 是否显示搜索框
				showColumns : false, // 是否显示内容下拉框（选择显示的列）
				sidePagination : "server",
                uniqueId: 'appLineId',
				queryParams : function(params) {
					return {
						//说明：传入后台的参数包括offset开始索引，limit步长，sort排序列，order：desc或者,以及所有列的键值对
						appId : appId,
                        orderBy:'seq'
					};
				},
                onLoadSuccess:function(data) {
                    if(data.code == 500){
                        layer.msg(data.msg);
                        return;
                    }
				    let item = data.list;
                    for(let index = 0;index< item.length;index++) {
                        if(item[index].receiptTime != null){
                            let agentString = item[index].agent == null||item[index].agent === '' ||  item[index].status===0
                                ? ''
                                : item[index].status === 5 ? ''
                                    : '[Proxy approval] '+item[index].receiverName+'/'+item[index].receiverJob
                                    + ' <i class="fa fa-long-arrow-right" aria-hidden="true"></i> '
                                    + item[index].agent.agentInfo +'&nbsp'+ '<br/>';

                            let remarkString = item[index].remark == null||item[index].remark === '' ? '' : item[index].remark+'&nbsp';

                            if(agentString!=='' || remarkString !==''){
                                $('#approvalLinesTable').bootstrapTable('insertRow', {index: index+1, row: {
                                        seq : index,
                                        handleType:item[index].handleType,
                                        handleTypeName : item[index].handleTypeName,
                                        receiverName : agentString + remarkString
                                    }
                                });
                            }
                        }
                    }
                    for(let index = 0;index< item.length;index++) {
                        if(item[index].receiptTime != null){
                            let agentString = item[index].agent == null||item[index].agent === '' || item[index].status === 0
                                ? ''
                                : item[index].status === 5 ? '' :'not null';

                            let remarkString = item[index].remark == null||item[index].remark === '' ? '' : 'not null';

                            if(agentString!=='' || remarkString !==''){
                                //合并列
                                $('#approvalLinesTable').bootstrapTable('mergeCells', { index: index+1, field: 'receiverName', colspan: 3, rowspan: 1 });
                                //合并行
                                $('#approvalLinesTable').bootstrapTable('mergeCells', { index: index, field: 'seq', colspan: 1, rowspan: 2 });
                                $('#approvalLinesTable').bootstrapTable('mergeCells', { index: index, field: 'handleTypeName', colspan: 1, rowspan: 2 });
                            }
                        }
                    }
                },
				// //请求服务器数据时，你可以通过重写参数的方式添加一些额外的参数，例如 toolbar 中的参数 如果
				// queryParamsType = 'limit' ,返回参数必须包含
				// limit, offset, search, sort, order 否则, 需要包含:
				// pageSize, pageNumber, searchText, sortName,
				// sortOrder.
				// 返回false将会终止请求
				columns : [
					{
						field : 'appDetailId',
						title : 'id',
						visible: false
					},
					{
						field : 'seq',
						title : 'No.',
						align : 'center',
                        valign : 'middle',
						width: '30px',
					},
					{
						field : 'handleTypeName',
						title : 'Type',
						width : '50px',
                        valign : 'middle',
                        cellStyle: function(value,row){
                            let color = '';
                            switch(row.handleType){
                                case 0://draft
                                    color = '#EFEFF0;';
                                    break;
                                case 1://approval
                                    color = '#CCE3F7;';
                                    break;
                                case 2://consent 4
                                    color = '#cfedf6;';
                                    break;
                                case 3:
                                    color = '#D0D7F0;';
                                    break;
                                case 4:
                                    color = '#cfedf6;';
                                    break;
                                case 7:
                                    color = '#CCE3F7;';
                                    break;
                                case 9://notification
                                    color = '#dadee0;';
                                    break;
                            }
                            return {
                                css : {
                                    'background-color' : color
                                }
                            };
                        },
                        formatter : function(value, row, index) {
                            switch(row.status){
                                case 1://同意
                                    switch(row.handleType){
                                        case 1://审批人
                                            value = 'Approved';
                                            break;
                                        case 2://协议人
                                            value = 'Consent';
                                            break;
                                        case 3://后批人
                                            value = 'Approved';
                                            break;
                                        case 4://平行合意人
                                            value = 'Parallel consent';
                                            break;
                                        case 7://平行审批人
                                            value = 'Parallel approved';
                                            break;
                                        case 9://
                                            value = 'Notification';
                                            break;
                                    }
                                    break;
                                case 2://驳回
                                    value = 'Reject';
                                    break;
                                case 3://特批
                                    value = 'Arbitrary decision';
                                    break;
                                case 5://自动审批
                                    switch(row.handleType){
                                        case 1://审批人
                                            value = 'Approval';
                                            break;
                                        case 2://协议人
                                            value = 'Consent';
                                            break;
                                        case 3://后批人
                                            value = 'Post approval';
                                            break;
                                        case 4://平行合意人
                                            value = 'Parallel consent';
                                            break;
                                        case 7://平行审批人
                                            value = 'Parallel approval';
                                            break;
                                        case 9://
                                            value = 'Notification';
                                            break;
                                    }
                                    break;
                            }
                            return value;
                        }
					},
					{
                        field : 'receiverName',
                        title : 'Name',
                        width: '150px',
                        cellStyle: function(value,row){
                            let color = '';
                            if(value.indexOf('&nbsp')>0){
                                switch(row.handleType){
                                    case 0://draft
                                        color = '#F7F7F7;';
                                        break;
                                    case 1://approval
                                        color = '#E5F1FB;';
                                        break;
                                    case 2://consent
                                        color = '#E7F6FA;';
                                        break;
                                    case 3://Post approval
                                        color = '#E7EBF7;';
                                        break;
                                    case 4://Parallel consent
                                        color = '#E7EBF7;';
                                        break;
                                    case 7://Parallel approval
                                        color = '#E7F6FA;';
                                        break;
                                    // case 9:
                                    //     color = '#E5F1FB;';
                                    //     break;
                                }
                            }
                            return {
                                css : {'background-color' :color}
                            }
                        },
                        formatter : function(value, row, index) {
                            if(value.indexOf('&nbsp') > 0){
                                return value;
                            }else{
                                let str = ''
                                    empId = '';

                                if(row.agentUserId != null && row.status !==5 && row.status !==0 ){//是代理人审批的，且不是自动审批的或者未审批的
                                    str = row.agent.agentInfo;
                                    empId = row.agentUserId
                                }else{
                                    str = value+'/'+row.receiverJob;
                                    empId = row.receiverEpid
                                }
                                var e = '<a href="#" title=\''+str+'\'  onclick="showEmp(\'' + empId + '\')">'+str+'</a> ';
                                return e;
                            }
                        }
                    },
					{
						field : 'handleTime',
						title : 'Processing date',
						width : '150px',
                        formatter : function(value, row, index) {
						    if(value == null){
                                if(row.handleType == 9){
                                    value = row.readTime;
                                }else{
                                    value = 'Pending';
                                }
                            }

                            return value;
                        }
					},
					{
						field : 'receiverDeptNm',
						title : 'Team',
						width : '40px',
						// formatter : function(value, row, index) {
                        //     return 'HPPS';
                        // }
					},
                    // {
					// 	field : 'remark',
					// 	title : 'Comments'
					// }
					]
			});
	dataFlag = true;
}

function calcPageSize() {
    var h = $('#westMaster').height() - 51 - 36 - 60;
    var pageSize = parseInt(h/35);
	return pageSize;
}

function clickSearchEvent() {
	var opt = {
		query: {
			title: $("#searchName").val().trim()
		}
	}
	$('#dataTable').bootstrapTable('refresh', opt);
	pageInit = $('#dataTable').bootstrapTable('getOptions').pageNumber + 1;
}

function searchByOpt(){
    if($('.main_search').hasClass('open')){
        $('.main_search').removeClass('open');
        $('#searchName').attr('aria-expanded',false);
    }

    var optTitle ='';
    var optAuthor ='';
    var optReceiptDate ='';
    var optSubmissionDate ='';
    var optCreationDate ='';
    var optApprovalDate ='';

    switch ($(this).attr("value")) {
        case 'title':
            optTitle=$("#searchName").val().trim();
            break;
        case 'author':
            optAuthor=$("#searchName").val().trim();
            break;
        case 'receiptDate':
            optReceiptDate=$("#searchName").val().trim();
            break;
        case 'submissionDate':
            optCreationDate=$("#searchName").val().trim();
            break;
        case 'creationDate':
            optCreationDate=$("#searchName").val().trim();
            break;
        case 'approvalDate':
            optApprovalDate=$("#searchName").val().trim();
            break;
    }
    var opt = {
        query: {
            title: optTitle,
            createUser:optAuthor,
            receiptTime:optReceiptDate,
            // submissionTime:optSubmissionDate,
            createTime:optCreationDate,
            handleTime:optApprovalDate
        }
    }
    if(optTitle !== ''||optAuthor !=='' || optReceiptDate !== '' || optSubmissionDate !== '' || optCreationDate !== '' || optApprovalDate !== ''){
        $('#dataTable').bootstrapTable('refresh', opt);
        pageInit = $('#dataTable').bootstrapTable('getOptions').pageNumber + 1;
    }
}

function clickStatusSelectEvent() {
    let value = $(this).data('value');
    let opt = {
		query: {
			title: $("#searchName").val().trim(),
            status:value,
            category:$("#ctgSelectValue").val()
		}
	}
	$("#statusSelectValue").val(value)
	$('#dataTable').bootstrapTable('refresh', opt);
	pageInit = $('#dataTable').bootstrapTable('getOptions').pageNumber + 1;
}

function clickCtgSelectEvent() {
    let value = $(this).data('value');

    let opt = {
		query: {
			title: $("#searchName").val().trim(),
            status:$("#statusSelectValue").val(),
            category:value
		}
	}
	$("#ctgSelectValue").val(value);
	$('#dataTable').bootstrapTable('refresh', opt);
	pageInit = $('#dataTable').bootstrapTable('getOptions').pageNumber + 1;
}

function searchEvent(event) {
	if(event.keyCode == "13"){
        var opt = {
            query : {
                title : $(this).val().trim()
            }
        }
        $('#dataTable').bootstrapTable('refresh', opt);
        pageInit = $('#dataTable').bootstrapTable('getOptions').pageNumber + 1;
	}
}

function loadAttachment(data){
    if($("#attachmentList li").length>0){
        $("#attachmentList").empty();
    }
    if(data != undefined && data.length >0){
        $.each( data, function( index, file ) {
            var type = file.fileType;
            var ico = '';
            if(type.indexOf('image')>-1){
                ico = "<span><i class='fa fa-file-image-o' style='color:#A03638' aria-hidden='true'></i></span>";
            }else if(type.indexOf('compressed')>-1){
                ico = "<span><i class='fa fa-file-archive-o' style='color:#F1B15A' aria-hidden='true'></i></span>";
            }else if(type.indexOf('word')>-1){
                ico = "<span><i class='fa fa-file-word-o' style='color:#2E5790' aria-hidden='true'></i></span>";
            }else if(type.indexOf('sheet')>-1){
                ico = "<span><i class='fa fa-file-excel-o' style='color:#1E7145' aria-hidden='true'></i></span>";
            }else{
                ico = "<span><i class='fa fa-file' style='color:#0096D6' aria-hidden='true'></i></span>";
            }
            $("#attachmentList").append(
                "<li>" +
//                    "<span class='my-checkbox'><input id='"+file.fileName+"' type='checkbox' hidden><label for='"+file.fileName+"'></label></span>" +
                    ico +
                    "<a id='fileUrl' href='/approval/download/"+file.fileOriginName+"/"+file.fileName+"' download='"+file.fileOriginName+"'>"+file.fileOriginName+"</a>" +
                    "<span id='fileSize'>("+(file.fileSize/1024).toFixed(2)+'KB'+")</span>" +
                    "<span id='operation'><i class='fa fa-download'></i></span>" +
                "</li>")
        });
        $("#detailFileIco").show();
        $("#attachmentInfo").show();
    }else{
        $("#attachmentInfo").hide();
        // $("#detailFileIco").hide();
        $("#detailFileIco").css('display','none')
    }
}

function loadContent(code){
    $('.summernote').summernote({
        lang : 'zh-CN'
    });
    $('#contentText').summernote('code',code);
    $('.summernote').summernote('destroy');
    $('.summernote').css('zoom','1');
}

function validateForm(layero,commentNeed) {
    let pwd = layero.find("iframe")[0].contentWindow.$("#password").val();
    let comment = layero.find("iframe")[0].contentWindow.$("#comment").val();
    if(pwd ===''){
        layer.msg("请输入密码")
        return false;
    }
    if(commentNeed!=undefined && comment ===''){
        layer.msg("请输入备注")
        return false;
    }

    if(!verifyPwd(pwd)){
        layer.msg("密码输入错误")
        return false;
    }
    return true;
}

function verifyPwd(pwd) {
    let animal = JSON.parse(sessionStorage.getItem("howAreYou"));
    return animal.password === $.md5(animal.empNm+pwd);
}

function detailEvent(){
	//$('#dataTable').bootstrapTable({locale: "en-US"});
    //$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['en-US']);

    $.ajax({
        url : prefix + "/create",
        type : "post",
        async:false,
        success : function(r) {
            if (r.code == 0) {
                console.log(r.msg);
            } else {
                alert(r.msg)
            }
        }
    });
}

function refreshEvent(){
    var opt = {
        query: {
            title: ''
        }
    }
    $('#dataTable').bootstrapTable('refresh',opt);
}

function showEmp(id){
	console.log(id);
}

function editApproval(){

}

function inquiryMail(){
    let appId = $("#appIdSpan").text();
    var url = "/approval/view/showStatusInquiry/"+appId; //转向网页的地址;
    var name = "Status inquiry"; //网页名称，可为空;
    var iWidth = "1008"; //弹出窗口的宽度;
    var iHeight = "670"; //弹出窗口的高度;
    //window.screen.height获得屏幕的高，window.screen.width获得屏幕的宽
    var iTop = (window.screen.height - 30 - iHeight) / 2; //获得窗口的垂直位置;
    var iLeft = (window.screen.width - 10 - iWidth) / 2; //获得窗口的水平位置;
    window.open(url, name, 'height=' + iHeight + ',innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no');
}

function unCheckEvent() {
    $('#dataTable').bootstrapTable('uncheckAll');
}

function batchDelMail(){
    var arr = [2,3,4,5];
    var targetData = $('#dataTable').bootstrapTable('getSelections');
    var result = true;
    $.each(targetData,function(index,row){
        if(arr.indexOf(row.status) == -1){
            result = false;
            return false;
        }
    });

    if(!result){
        //有些不能删
        layer.alert('Only in cases were they were completed, rejected, arbitrary approved can be deleted.',{
            closeBtn: 0,
            btn: ['OK'],
            title: 'Notification',
            shade: [0.1,'#fff']
        });
        return;
    }

    layer.confirm('Are you sure to delete the approvals ?', {
            shade: 0,
            closeBtn: 0,
            shade: [0.1,'#fff'],
            title:'Notification',
            btn: ['Yes','No'] //按钮
        }, function(index){
            $.ajax({
                url : prefix + "/batchDelete",
                type : "post",
                traditional: true,
                data:{
                    appLineIds: wrapper.selectAppLineIds
                },
                success : function(r) {
                    if(r.code==0){
                        asyncRefreshPage()
                        wrapper.selectAppLineIds.length = 0
                        wrapper.selectRowsTotal = 0;
                        layer.close(index);
                        layer.msg("Delete successfully.");
                    }else{
                        layer.msg(r.msg);
                        return;
                    }
                }
            });
        }, function(){

        });
}

function delMail(){
    layer.confirm('Are you sure to delete the approval ?', {
            shade: 0,
            closeBtn: 0,
            title:'Notification',
            btn: ['Yes','No'] //按钮
        }, function(index){
            var appId = $("#appIdSpan").text();
            $.ajax({
                url : prefix + "/delete/"+appId,
                type : "delete",
                contentType:'json',
                success : function(r) {
                    if(r.code==0){
                        layer.msg(r.msg);
                        asyncRefreshPage();
                        layer.close(index);
                    }else{
                        layer.msg(r.msg);
                        return;
                    }
                }
            });
        }, function(){

        });
}

function asyncRefreshPage() {
    $('#selected').hide();
    $('.detailBody').hide();
    $('#noSelected').show();
    $('#dataTable').bootstrapTable('refresh');
    pageInit = $('#dataTable').bootstrapTable('getOptions').pageNumber + 1;
}

function reLoad(appId) {
	var opt = {
		query : {
			appId : appId,
		}
	}
	$('#approvalLinesTable').bootstrapTable('refresh', opt);
}

function collapsewest(){
	if($("#noSelected").is(":hidden")){
		//$('#content').layout('collapse','west');

		// 获取标识数据
		var dataId = $(this).find("#appIdSpan").text(),
			flag = true,
			menuName = $("#detailTopTitle").text(),

			src = '/approval/view/showPendingDetail?appId='+dataId;
		if (dataId == undefined || $.trim(dataId).length == 0)return false;

	    // 选项卡菜单已存在
	    $('.J_menuTab',parent.document).each(function () {
	        if ($(this).data('id') == dataId) {
	            if (!$(this).hasClass('active')) {
	                $(this).addClass('active').siblings('.J_menuTab').removeClass('active');
	                scrollToTab(this);
	                // 显示tab对应的内容区
	                $('.J_mainContent .J_iframe',parent.document).each(function () {
	                    if ($(this).data('id') == dataId) {
	                        $(this).show().siblings('.J_iframe').hide();
	                        return false;
	                    }
	                });
	            }

	            flag = false;
	            return false;
	        }
	    });

	    // 选项卡菜单不存在
	    if (flag) {
	        var str = '<a href="javascript:;" title="'+menuName+'" class="active J_menuTab" data-id="' + dataId + '"><span id="mName">' + menuName + '</span>&#12288;<i class="fa fa-times"></i></a>';
	        $('.J_menuTab',parent.document).removeClass('active');

	        // 添加选项卡对应的iframe
	        var str1 = '<iframe class="J_iframe" name="iframe' + dataId + '" width="100%" height="100%" src="' + src + '" frameborder="0" data-id="' + dataId + '" seamless></iframe>';
	        $('.J_mainContent',parent.document).find('iframe.J_iframe').hide().parents('.J_mainContent').append(str1);

	        // 添加选项卡
	        $('.J_menuTabs .page-tabs-content',parent.document).append(str);
	        scrollToTab($('.J_menuTab.active',parent.document));
	    }
	    return false;
	}
}

function collapseBox(){
	$(this).children('.fa-arrow-left').toggleClass('hidden');
	$(this).children('.fa-arrow-right').toggleClass('hidden');

	var p = $("#content").layout("panel", "west")[0].clientWidth;
    if (p > 0){
        $('#content').layout('collapse', 'west');
        $(this).attr("title","Reduce view window");
    }
    else{
    	 $('#content').layout('expand', 'west');
    	$(this).attr("title","Expand view window");
    }
}

function printEvent() {
    let appId = $("#appIdSpan").text();
    if(appId ==''){
        return false;
    }
    var url = "/approval/view/showPrintApproval/"+appId; //转向网页的地址;
    var name = "Print Approval"; //网页名称，可为空;
    var iWidth = "1008"; //弹出窗口的宽度;
    var iHeight = "670"; //弹出窗口的高度;
    //window.screen.height获得屏幕的高，window.screen.width获得屏幕的宽
    var iTop = (window.screen.height - 30 - iHeight) / 2; //获得窗口的垂直位置;
    var iLeft = (window.screen.width - 10 - iWidth) / 2; //获得窗口的水平位置;
    window.open(url, name, 'height=' + iHeight + ',innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no');
}

function maxEvent(obj) {
    $(obj,document).children('.fa-arrows-alt').toggleClass('hidden');
	$(obj,document).children('.fa-compress').toggleClass('hidden');

    if ($(obj).children('.fa-compress').is(':hidden')){
        $('.mainBody nav',window.parent.document).eq(0).css({
            'height': 'calc(100% - 66px)'
        });
        $('#wrapper nav',window.parent.document).eq(0).css({
            'display':'block'
        });

        $('body',window.parent.document).removeClass('mini-navbar');

        $('#page-wrapper',window.parent.document).css({
            'padding': '0 13px',
            'position': 'inherit',
            'margin': '0 0 0 17em'
        });

        $(obj).attr('title','max view');
    }
    else{
        $('.mainBody nav',window.parent.document).eq(0).css({
            'height': 'calc(100% - 20px)'
        });
        $('#wrapper nav',window.parent.document).eq(0).css({
            'display':'none'
        });

        $('body',window.parent.document).addClass('mini-navbar');

        $('#page-wrapper',window.parent.document).css({
            'height':'100%',
            'position' : 'fixed',
            "top": "0px",
            "left": "80px",
            "right": "0px",
            "bottom": "0px",
            'margin':'auto',
            'z-index': '2002'
        });

    	$(obj).attr('title','restore view');
    }
}

function zoomInEvent() {
    let value = Number($('.summernote').css('zoom'));

    if(value < 2.5){
        value += 0.25;
        $('.summernote').css({
            'zoom':value
        })
    }else{
        $('.summernote').css({
            '-moz-transform-origin': 'top left',
            '-ms-transform-origin': 'top left',
            '-moz-transform'           : 'scale(1.5)', /*Firefox*/
            '-ms-transform'            : 'scale(1.5)' /*IE*/
        })
    }
}

function zoomOutEvent() {
    let value = Number($('.summernote').css('zoom'));

    if(value > 0.5){
        value -= 0.25;
        $('.summernote').css('zoom',value)
    }else{
        $('.summernote').css({
            '-moz-transform-origin': 'top left',
            '-ms-transform-origin': 'top left',
            '-moz-transform'           : 'scale(1)', /*Firefox*/
            '-ms-transform'            : 'scale(1)' /*IE*/
        })
    }
}

function foldEvent(){
	$(this).children('.fa-angle-down').toggleClass('hidden');
	$(this).children('.fa-angle-up').toggleClass('hidden');


    if ($(this).children('.fa-angle-down').is(':hidden')){
        $('#foldLineSpan').text("Expose approval line");
    }
    else{
    	$('#foldLineSpan').text("Fold approval line");
    }

	$(".detailBody .bootstrap-table").slideToggle(100);
}

function foldTopEvent(){
	$(this).children('.fa-angle-down').toggleClass('hidden');
	$(this).children('.fa-angle-up').toggleClass('hidden');

    if($(this).children('.fa-angle-up').hasClass('hidden')){//expand
        $(".detailTop").height($(".detailTop").height() + $(".detailAuthorAndTime").outerHeight(true));
        $(".detailBody").height($(".detailBody").height() - $(".detailAuthorAndTime").outerHeight(true));

        if(!$('div.media-pdf').is(":hidden")){
            $('div.media-pdf').css('top',parseFloat($('div.media-pdf').css('top').substring(0,$('div.media-pdf').css('top').length-2))+$(".detailAuthorAndTime").outerHeight(true)+'px');
            $('div.media-pdf').height($('div.media-pdf').outerHeight(true)- $(".detailAuthorAndTime").outerHeight(true));
        }
    }else{//collapse
        $(".detailTop").height($(".detailTop").height() - $(".detailAuthorAndTime").outerHeight(true));
        $(".detailBody").height($(".detailBody").height() + $(".detailAuthorAndTime").outerHeight(true));
        if(!$('div.media-pdf').is(":hidden")){
            $('div.media-pdf').css('top',$('div.media-pdf').css('top').substring(0,$('div.media-pdf').css('top').length-2)-$(".detailAuthorAndTime").outerHeight(true)+'px')
            $('div.media-pdf').height($('div.media-pdf').outerHeight(true)+ $(".detailAuthorAndTime").outerHeight(true))
        }
    }

	$(".detailAuthorAndTime").toggle();
}

function maxView(appId,title){
		// 获取标识数据
		var dataId = appId,
			flag = true,
			menuName = title,

			src = '/approval/view/showPendingDetail?appId='+appId;
		if (dataId == undefined || $.trim(dataId).length == 0)return false;

	    // 选项卡菜单已存在
	    $('.J_menuTab',parent.document).each(function () {
	        if ($(this).data('id') == dataId) {
	            if (!$(this).hasClass('active')) {
	                $(this).addClass('active').siblings('.J_menuTab').removeClass('active');
	                scrollToTab(this);
	                // 显示tab对应的内容区
	                $('.J_mainContent .J_iframe',parent.document).each(function () {
	                    if ($(this).data('id') == dataId) {
	                        $(this).show().siblings('.J_iframe').hide();
	                        return false;
	                    }
	                });
	            }

	            flag = false;
	            return false;
	        }
	    });

	    // 选项卡菜单不存在
	    if (flag) {
	        var str = '<a href="javascript:;" title="'+menuName+'" class="active J_menuTab" data-id="' + dataId + '"><span id="mName">' + menuName + '</span>&#12288;<i class="fa fa-times"></i></a>';
	        $('.J_menuTab',parent.document).removeClass('active');

	        // 添加选项卡对应的iframe
	        var str1 = '<iframe class="J_iframe" name="iframe' + dataId + '" width="100%" height="100%" src="' + src + '" frameborder="0" data-id="' + dataId + '" seamless></iframe>';
	        $('.J_mainContent',parent.document).find('iframe.J_iframe').hide().parents('.J_mainContent').append(str1);

	        // 添加选项卡
	        $('.J_menuTabs .page-tabs-content',parent.document).append(str);
	        scrollToTab($('.J_menuTab.active',parent.document));
	    }
	    return false;
}

//滚动到指定选项卡
function scrollToTab(element) {
    var marginLeftVal = calSumWidth($(element).prevAll()), marginRightVal = calSumWidth($(element).nextAll());
    // 可视区域非tab宽度
    var tabOuterWidth = calSumWidth($(".content-tabs").children().not(".J_menuTabs"));
    //可视区域tab宽度
    var visibleWidth = $(".content-tabs").outerWidth(true) - tabOuterWidth;
    //实际滚动宽度
    var scrollVal = 0;
    if ($(".page-tabs-content").outerWidth() < visibleWidth) {
        scrollVal = 0;
    } else if (marginRightVal <= (visibleWidth - $(element).outerWidth(true) - $(element).next().outerWidth(true))) {
        if ((visibleWidth - $(element).next().outerWidth(true)) > marginRightVal) {
            scrollVal = marginLeftVal;
            var tabElement = element;
            while ((scrollVal - $(tabElement).outerWidth()) > ($(".page-tabs-content").outerWidth() - visibleWidth)) {
                scrollVal -= $(tabElement).prev().outerWidth();
                tabElement = $(tabElement).prev();
            }
        }
    } else if (marginLeftVal > (visibleWidth - $(element).outerWidth(true) - $(element).prev().outerWidth(true))) {
        scrollVal = marginLeftVal - $(element).prev().outerWidth(true);
    }
    $('.page-tabs-content').animate({
        marginLeft: 0 - scrollVal + 'px'
    }, "fast");
}

function calSumWidth(elements) {
    var width = 0;
    $(elements).each(function () {
        width += $(this).outerWidth(true);
    });
    return width;
}